package me.firstapp.spi.shop.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.shop.JsonAddress;
import me.firstapp.spi.base.impl.BaseServiceImpl;
import me.firstapp.spi.shop.AddressService;

@Service
public class AddressServiceImpl extends BaseServiceImpl implements AddressService {

	@Override
	public SingleObject<JsonAddress> addUpdateAddress(Long memberId, String name, String mobile, String province,
			String city, String district, String detail) {
		SingleObject<JsonAddress> result = new SingleObject<JsonAddress>();
		try {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("memberId", memberId);
			parameters.put("name", name);
			parameters.put("mobile", mobile);
			parameters.put("province", province);
			parameters.put("city", city);
			parameters.put("district", district);
			parameters.put("detail", detail);

			JSONObject resultObject = api(parameters, "/address/addUpdateAddress.do", HttpMethod.POST, "新增/更新收货地址");

			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultObject.getString("code"))) {
				JsonAddress address = JSONObject.toJavaObject(resultObject.getJSONObject("object"),
						JsonAddress.class);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
				result.setObject(address);
			} else {
				throw new ServiceException(resultObject.getString("code"), resultObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

	@Override
	public SingleObject<JsonAddress> findAddressByMemberId(Long memberId) {
		SingleObject<JsonAddress> result = new SingleObject<JsonAddress>();
		try{
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("memberId", memberId);
			JSONObject resultObject = api(parameters, "/address/findAddressByMemberId.do", HttpMethod.GET, "查询用户收货地址");

			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultObject.getString("code"))) {
				JsonAddress address = JSONObject.toJavaObject(resultObject.getJSONObject("object"), JsonAddress.class);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
				result.setObject(address);
			} else {
				throw new ServiceException(resultObject.getString("code"), resultObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

}
